package com.acane.instagram.core.config

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import com.acane.instagram.core.model.Notification
import com.acane.instagram.feature.chat.ChatWebSocketClient
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Response

// WebSocketManager.kt
object WebSocketManager {
    private var chatWebSocketClient: ChatWebSocketClient? = null
    private val listeners = mutableListOf<ChatWebSocketClient.Listener>()
    private var isAppInForeground = false

    // 在类顶部添加状态维护变量
    private val _isConnected = mutableStateOf(false)
    val isConnected: Boolean
        get() = _isConnected.value


    // WebSocketManager.kt 修改后的方法
    fun sendNotification(notification: Notification) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val json = notification.toMessageJson()
                chatWebSocketClient?.webSocket?.send(json)
                Log.d("WebSocket", "发送${json}通知成功")
            } catch (e: Exception) {
                Log.e("WebSocket", "发送${notification.type}通知失败", e)
            }
        }
    }
    // 添加/移除监听器方法
    fun addListener(listener: ChatWebSocketClient.Listener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener)
        }
    }

    fun removeListener(listener: ChatWebSocketClient.Listener) {
        listeners.remove(listener)
    }

    fun connect(sessionId: String) {
        // 添加连接前检查
        if (isConnected) {
            Log.w("WebSocketManager", "Already connected, skip reconnect")
            return
        }
        // 先关闭旧连接
        disconnect()

        chatWebSocketClient = ChatWebSocketClient(object : ChatWebSocketClient.Listener {
            override fun onMessageReceived(message: Notification) {

                listeners.forEach { it.onMessageReceived(message) }
            }

            override fun onConnected() {
                _isConnected.value = true
                listeners.forEach { it.onConnected() }
            }

            override fun onClosed(code: Int, reason: String) {
                _isConnected.value = false
                listeners.forEach { it.onClosed(code, reason) }
            }

            override fun onFailure(t: Throwable, response: Response?) {
                _isConnected.value = false
                listeners.forEach { it.onFailure(t, response) }
            }
        })
        CoroutineScope(Dispatchers.IO).launch {
            try {
                chatWebSocketClient?.connect("ws://10.0.2.2:8081/chat", sessionId)
            } catch (e: Exception) {
                Log.e("WebSocketManager", "连接失败: ${e.message}")
            }
        }
    }

    fun disconnect() {
        chatWebSocketClient?.close()
    }

    fun setAppForegroundState(inForeground: Boolean) {
        isAppInForeground = inForeground
        if (inForeground) {
            SessionManager._sessionId?.let { connect(it) }
        } else {
            disconnect()
        }
    }
}
